/*
 * libustream: User-space stackable streams
 * @(#) $Id: http.c 2 2009-02-20 09:52:11Z mo@ilaven.net $
 */

/*
 * Copyright (c) 2002, 2008 Mo McRoberts.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The names of the author(s) of this software may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * AUTHORS OF THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "p_usmodules.h"

/* This module implements stream support for HTTP connections. Essentially,
 * there are three different kinds of HTTP stream:
 * - An HTTP listener (this cannot be read or written to, but accepts connections)
 *   A listener is opened by passing O_CREAT in @oflag in the call to create
 *   the stream object.
 * - An HTTP client connection
 *   The HTTP request headers will not be sent until the Payload-size
 *   property is set, which is mapped to the Content-length HTTP header. Data
 *   written to the stream will be passed to the next node in the stack until
 *   Payload-size bytes have been written.
 * - An HTTP server connection
 *   A server connection is soley via the Accept method on a listener stream.
 */

static com_result_t __stdcall UStream_HTTP_QueryInterface(IUStreamNode *intf, com_riid_t iid, void **out);
static uint32_t __stdcall UStream_HTTP_AddRef(IUStreamNode *intf);
static uint32_t __stdcall UStream_HTTP_Release(IUStreamNode *intf);
static com_result_t __stdcall UStream_HTTP_GetChildNode(IUStreamNode *intf, IUStream *parent, IUStream *child, IUStreamNode **childNode);
static com_result_t __stdcall UStream_HTTP_Write(IUStreamNode *intf, IUStream *stream, const void *buf, size_t *buflen);
static com_result_t __stdcall UStream_HTTP_Read(IUStreamNode *intf, IUStream *stream, void *buf, size_t *buflen);
static com_result_t __stdcall UStream_HTTP_Pending(IUStreamNode *intf, IUStream *stream, size_t *out);
static com_result_t __stdcall UStream_HTTP_Accept(IUStreamNode *intf, IUStream *stream, IUStreamNode **out, int *fdout);

typedef enum
{
	HTTP_LISTENER = 1,
	HTTP_CLIENT = 2,
	HTTP_SERVER = 3
} http_type_t;
	
typedef enum
{
	HTTP_STATE_METHOD,
	HTTP_STATE_HEADER_NAME,
	HTTP_STATE_HEADER_VALUE,
	HTTP_STATE_PAYLOAD
} http_state_t;

DECLARE_CLASS(UStream_HTTP)
{
	DECLARE_IMPLEMENTS(UStream_HTTP, IUStreamNode);
	uint32_t refcount;
	http_type_t type;
	http_state_t rstate;
	http_state_t wstate;
};

DEFINE_CLASS_INTERFACE(UStream_HTTP, IUStreamNode)
{
	UStream_HTTP_QueryInterface,
	UStream_HTTP_AddRef,
	UStream_HTTP_Release,
	UStream_HTTP_GetChildNode,
	UStream_HTTP_Write,
	UStream_HTTP_Read,
	UStream_HTTP_Pending,
	UStream_HTTP_Accept
};

extern com_result_t
us__http_push(IUStream *stream, IUStreamNode **out)
{
	UStream_HTTP *f;
	
	(void) stream;
	
	if(NULL == (f = (UStream_HTTP *) calloc(1, sizeof(UStream_HTTP))))
	{
		return errno;
	}
	f->type = HTTP_LISTENER;
	INITIALISE_ADDREF_INTERFACE_POINTER(UStream_HTTP, f, IUStreamNode);
	*out = GET_INTERFACE_POINTER(f, IUStreamNode);
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_HTTP_QueryInterface(IUStreamNode *intf, com_riid_t iid, void **out)
{
	if(com_guid_equal(iid, &IID_IUnknown) || com_guid_equal(iid, &IID_IUStreamNode))
	{
		UStream_HTTP_AddRef(intf);
		*out = (void *) intf;
		return COM_S_OK;
	}
	return COM_E_NOINTERFACE;
}

static uint32_t __stdcall
UStream_HTTP_AddRef(IUStreamNode *intf)
{
	DECLARE_SELF(UStream_HTTP, IUStreamNode, intf);
	
	self->refcount++;
	return self->refcount;
}

static uint32_t __stdcall
UStream_HTTP_Release(IUStreamNode *intf)
{
	DECLARE_SELF(UStream_HTTP, IUStreamNode, intf);
	
	self->refcount--;
	if(0 == self->refcount)
	{
		free(self);
		return 0;
	}
	return self->refcount;
}

static com_result_t __stdcall
UStream_HTTP_Write(IUStreamNode *intf, IUStream *stream, const void *buf, size_t *buflen)
{
	DECLARE_SELF(UStream_HTTP, IUStreamNode, intf);

	(void) stream;

	if(HTTP_LISTENER == self->type)
	{
		return EINVAL;
	}
	if(HTTP_STATE_PAYLOAD != self->wstate)
	{
		/* Send headers */
	}
/*	fprintf(stderr, "Writing %d bytes\n", (int) (*buflen)); */
	return IUStream_Write(stream, buf, buflen);
}

static com_result_t __stdcall
UStream_HTTP_Read(IUStreamNode *intf, IUStream *stream, void *buf, size_t *buflen)
{
	(void) intf;
	
	return IUStream_Read(stream, buf, buflen);
}

static com_result_t __stdcall
UStream_HTTP_GetChildNode(IUStreamNode *intf, IUStream *parent, IUStream *child, IUStreamNode **childNode)
{
	UStream_HTTP *f;
	const char *s;
	size_t len;
	
	(void) intf;
	(void) parent;
	(void) child;
	
	if(NULL == (f = (UStream_HTTP *) calloc(1, sizeof(UStream_HTTP))))
	{
		return errno;
	}
	f->type = HTTP_SERVER;
	INITIALISE_ADDREF_INTERFACE_POINTER(UStream_HTTP, f, IUStreamNode);
	*childNode = GET_INTERFACE_POINTER(f, IUStreamNode);
	s = "HTTP/1.0 200 OK\n"
		"Server: Eregansu\n"
		"Content-type: text/html\n"
		"Connection: close\n"
		"\n"
		"<!DOCTYPE html>\n"
		"<html><head><title>Eregansu</title><body><h1>Hello!</h1><p>…world!</p><hr /><div><address>Eregansu HTTP server</address></div></body></html>\n";
	len = strlen(s);
	IUStream_Write(child, s, &len);
	return COM_S_OK;
}

static com_result_t __stdcall
UStream_HTTP_Accept(IUStreamNode *intf, IUStream *stream, IUStreamNode **out, int *fdout)
{
	/* For non-head nodes, we pass through to the next node in the stack.
	 * Upon successful accept, IUStream::GetChildNode() will be called for each
	 * node in the parent’s stack, passing the new stream object.
	 * GetChildNode() is one of the few methods which shouldn't be passed
	 * along the stack.
	 */
	return IUStream_ForwardAccept(stream, out, fdout);
}

static com_result_t __stdcall
UStream_HTTP_Pending(IUStreamNode *intf, IUStream *stream, size_t *out)
{
	int len;
	
	DECLARE_SELF(UStream_HTTP, IUStreamNode, intf);
	
	return IUStream_Pending(stream, out);
}
